package com.hand.wfive.base;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.hand.wfive.loginAndVip.ApiConfig;
import com.hand.wfive.loginAndVip.MD5Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class ResponseInterceptor implements Interceptor {
    private static final String TAG = "ResponseInterceptor";

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        //返回request
        Request request = chain.request();
        HttpUrl originalUrl = request.url();
        //返回response
        Response response = chain.proceed(request);
        if (ApiConfig.isEncryptApi(originalUrl.toString())) {
            //isSuccessful () ; 如果代码在[200..300]中，则返回true，这意味着请求已成功接收、理解和接受。
            if (response.isSuccessful()) {
                //返回ResponseBody
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    try {
                        //获取bodyString
                        BufferedSource source = responseBody.source();
                        source.request(Long.MAX_VALUE);
                        Buffer buffer = source.buffer();
                        Charset charset = StandardCharsets.UTF_8;
                        MediaType contentType = responseBody.contentType();
                        if (contentType != null) {
                            charset = contentType.charset(charset);
                        }
                        String bodyString = buffer.clone().readString(charset);
                        try {
                            JSONObject jsonObject = new JSONObject(bodyString);

                            if (jsonObject.optInt("code") == ApiConfig.SUCCESSCODE) {
                                String jsonStr = jsonObject.optString("data");
                                String md5Str = MD5Utils.getMd5Str(jsonStr);
                                String objKey = jsonObject.optString("objKey");

                                if (TextUtils.equals(objKey, md5Str)) {
                                    JSONObject jsonObjectNew = new JSONObject(jsonStr);
                                    jsonObject.put("obj", jsonObjectNew);
                                    ResponseBody modifiedBody = ResponseBody.create(contentType, jsonObject.toString());
                                   /* Log.d("testXX", "-------------------------------------");
                                    Log.d("testXX", "" + jsonObject);
                                    Log.d("testXX", "-------------------------------------");*/
                                    return response.newBuilder().body(modifiedBody).build();
                                } else {
                                    Log.d("testXX", "=================登录失败，请检查您的账号信息！==================" );
                                    JSONObject jsonObjectNew = new JSONObject();
                                    jsonObjectNew.put("code" , ApiConfig.USERCHANGEINFOCODE);
                                    jsonObjectNew.put("msg" ,"登录失败，请检查您的账号信息！");
                                    ResponseBody modifiedBody = ResponseBody.create(contentType, jsonObjectNew.toString());
                                    return response.newBuilder().body(modifiedBody).build();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return response;
                        }
                    } catch (IOException e) {
                        //如果发生异常直接返回
                        e.printStackTrace();
                        return response;
                    }
                } else {
                    Log.i(TAG, "onHttpResultResponse: 响应体为空");
                }
            }
        }
        return response;
    }

}